﻿using Abp.Runtime.Session;
using Abp.Timing;
using DotNetCore.CAP;
using Hicap.QRCodeWarehouse.Core.Common;
using Hicap.QRCodeWarehouse.Core.EFCore;
using Hicap.QRCodeWarehouse.Core.Models.DbSet;
using Newtonsoft.Json;
using Serilog;

namespace Hicap.QRCodeWarehouse.Core.Managers
{
    public class ProductManager : ManagerBase<Product>, IProductManager
    {
        private readonly ICapPublisher _capBus;
        private readonly IAbpSession _session;

        public ProductManager(IUnitOfWork unitOfWork, IAbpSession session, ICapPublisher capBus) : base(unitOfWork)
        {
            _session = session;
            _capBus = capBus;
            ForeignKeys.Add(x => x.OuterGenerationRule);
            ForeignKeys.Add(x => x.InnerGenerationRule);

            QueryCondition.Add(x => x.IsDeleted == false);

            int? companyId = session.GetCompanyId();
            if (companyId.HasValue) QueryCondition.Add(x => x.SubordinateCompanyId == companyId.Value);

            CreateActions.Add(x => x.CreatorUserId = session.UserId);
            CreateActions.Add(x => x.CreationTime = Clock.Now);
            UpdateActions.Add(x => x.LastModificationTime = Clock.Now);
            UpdateActions.Add(x => x.LastModifierUserId = session.UserId);
            DeleteActions.Add(x => x.DeletionTime = Clock.Now);
            DeleteActions.Add(x => x.DeleterUserId = session.UserId);
            DeleteActions.Add(x => x.IsDeleted = true);

            CreateCheckActions.Add(x =>
            {
                if (x.Id == 0) return true;
                Log.Warning($"Product CreateCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
            UpdateCheckActions.Add(x =>
            {
                if (x.Id > 0 && x.IsDeleted == false) return true;
                Log.Warning($"Product UpdateCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
            DeleteCheckActions.Add(x =>
            {
                if (x.IsDeleted == false) return true;
                Log.Warning($"Product DeleteCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
        }
    }
}